package com.ng.common.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ng.common.util.SqlInjectionUtil;
import com.ng.common.util.XssUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;

@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("Request URI: {}", request.getRequestURI());

		// 检查请求路径是否存在 SQL 注入风险
		if (SqlInjectionUtil.containsSqlInjection(request.getRequestURI())) {
			log.warn("Potential SQL injection detected in request URI: {}", request.getRequestURI());
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Potential SQL injection detected.");
			return false;
		}

		// 检查请求参数是否存在 SQL 注入和 XSS 风险
		AtomicBoolean isContainsSqlInjection = new AtomicBoolean(false);
		AtomicBoolean isXss = new AtomicBoolean(false);
		request.getParameterMap().forEach((key, values) -> {
			for (String value : values) {
				if (SqlInjectionUtil.containsSqlInjection(value)) {
					log.warn("Potential SQL injection detected in parameter: {}={}", key, value);
					isContainsSqlInjection.set(true);
					break;
				}
				
				if (XssUtil.containsXss(value)) {
					log.warn("Potential XSS detected in parameter: {}={}", key, value);
					isXss.set(true);
					break;
				}
				
			}
		});

		if (isContainsSqlInjection.get()) {
			log.warn("Potential SQL injection detected in request parameters.");
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Potential SQL injection detected.");
			return false;
		}
		
		if (isXss.get()) {
			log.warn("Potential XSS detected in request parameters.");
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Potential XSS detected.");
			return false;
		}

		// 检查请求体（仅适用于 POST 请求）
		if ("POST".equalsIgnoreCase(request.getMethod())) {
			String body = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);
			if (SqlInjectionUtil.containsSqlInjection(body)) {
				log.warn("Potential SQL injection detected in request body.");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Potential SQL injection detected.");
				return false; // 终止请求
			}
		}

		log.info("Request passed all checks.");
		return true; // 继续处理请求
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.info("Response Status: {}", response.getStatus());
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("Request completed for URI: {}", request.getRequestURI());
		if (ex != null) {
			log.error("Exception occurred: {}", ex.getMessage());
		}
	}
}